<template>
  <div>
    <el-steps style="max-width: 600px" :space="200" :active="active" finish-status="finish">
      <!-- 
      process-status="success"'wait' | 'process' | 'finish' | 'error' | 'success' -->
      <el-step title="验证原邮箱" />
      <el-step title="验证新邮箱" />
      <el-step title="邮箱修改完毕" />
    </el-steps>
    <el-form ref="oldEmailFormRef" class="oldEmail" :model="oldEmailInf" :rules="rules" label-width="80px" v-if="active == 1">
      <el-form-item style="max-width: 600px" label="原邮箱" prop="email">
        <el-input class="email" v-model="oldEmail" disabled type="email" auto-complete="off" maxlength="200px"
          placeholder="邮箱">
          <template #prefix>
            <el-icon>
              <Suitcase />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item style="max-width: 600px" class="code" label="验证码" prop="code">
        <el-input v-model="oldEmailInf.code" auto-complete="off" placeholder="验证码" style="width: 65%"
          @keyup.enter.native="next">
          <template #prefix>
            <el-icon>
              <Message />
            </el-icon>
          </template>
        </el-input>
        <div class="register-code" style="width: 35%">
          <el-button style="width: 100%;height: 100%;" :disabled="isDisable" type="primary" @click="getCode(oldEmail)">
            {{ disableTime != 0 ? disableTime + 's' : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="next">{{ loading ? "正在验证" : '下一步' }}</el-button>
      </el-form-item>
    </el-form>

    <el-form ref="newEmailFormRef" class="oldEmail" :model="newEmailInf" :rules="rules" label-width="80px" v-if="active == 2">
      <el-form-item label="新邮箱" prop="email">
        <el-input class="email" v-model="newEmailInf.email" type="email" auto-complete="off" maxlength="200px"
          placeholder="邮箱">
          <template #prefix>
            <el-icon>
              <Suitcase />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="code" label="验证码" prop="code">
        <el-input v-model="newEmailInf.code" auto-complete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter.native="updateEmail">
          <template #prefix>
            <el-icon>
              <Message />
            </el-icon>
          </template>
        </el-input>
        <div class="register-code">
          <el-button style="width: 100%;height: 100%;" :disabled="isDisable" type="primary"
            @click="getCode(newEmailInf.email)">
            {{ disableTime != 0 ? disableTime + 's' : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateEmail()">{{ loading ? "正在验证" : '提交' }}</el-button>
      </el-form-item>
    </el-form>
    <el-card v-if="active == 3">
      <p>修改邮箱成功。</p>
    </el-card>
  </div>
</template>

<script>
import useUserStore from "@/store/modules/user";
import { getEmailCodeImg } from "@/api/login";
import { checkCode, resetEmail } from "@/api/forum/student";
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      loading: false,
      active: 1,
      oldEmailInf: {
        email: '',
        code: null,
      },
      newEmailInf: {
        email: '',
        code: null,
      },
      disableTime: 0,
      isDisable: false,
      interval: null,
      isSuccess: false,
      rules: {
        email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
        code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
      }
    }
  },
  computed: {
    oldEmail() {
      this.oldEmailInf.email = useUserStore().email;
      // console.log(this.oldEmail)
      return useUserStore().email;
    }
  },
  created() {
  },
  methods: {
    getCode(email) {
      // console.log('oldEmail', this.oldEmail)
      // console.log('oldEmailInf', this.oldEmailInf.email)
      if (email != null && email != '') {
        if (this.validateEmail(email)) {
          var query = {
            email: email
          }
          getEmailCodeImg(query).then(res => {
            if (res.code == 200) {
              this.isDisable = true;
              this.disableTime = 120;
              this.interval = setInterval(() => {
                this.disableTime = this.disableTime - 1;
              }, 1000)
              ElMessage({
                message: res.msg,
                type: 'success'
              });
            }
          });
        } else {
          ElMessage.error("邮箱格式有误，请输入正确邮箱。");
        }
      } else {
        ElMessage.error("请输入邮箱后，在点击发送验证码。");
      }
    },
    next() {
      this.$refs.oldEmailFormRef.validate(valid => {
        if(valid){
          this.loading = true;
          var data = {
            email: this.oldEmail,
            code: this.oldEmailInf.code
          }
          checkCode(data).then(res => {
            if (res.code == 330) {
              // ElMessage.error(res.msg);
            } else if (res.code == 200) {
              ElMessage({
                showClose: true,
                message: '验证码成功。',
                type: 'success',
              })
              this.active = 2;
            } else {
              ElMessage({
                showClose: true,
                message: '验证码错误',
                type: 'error',
              })
            }
              this.loading = false;
            this.disableTime = 0;
            this.isDisable = false;
            clearTimeout(this.interval);
          }).catch(() => {
            this.loading = false;
          })
        }
      })
    },
    updateEmail() {
      this.$refs.newEmailFormRef.validate(valid => {
        if(valid){
          this.loading = true;
          var data = {
            id: useUserStore().id,
            email: this.newEmailInf.email,
            code: this.newEmailInf.code
          }
          resetEmail(data).then(res => {
            if (res.code == 330) {
              // ElMessage.error(res.msg);
            } else if (res.code == 200) {
              ElMessage({
                showClose: true,
                message: '修改邮箱成功。',
                type: 'success',
              })
              this.isSuccess = true;
              this.active = 3;
            } else {
              ElMessage({
                showClose: true,
                message: '修改邮箱失败',
                type: 'error',
              })
              this.isSuccess = false;
            }
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          })
        }
      })
      
    },
    validateEmail(email) {
      var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    },
  },
  watch: {
    'disableTime': {
      handler() {
        if (this.disableTime == 0) {
          clearTimeout(this.interval);
        }
      },
      // 强制立即执行回调
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.oldEmail {
  margin: 20px 20px 20px 20px;

  .email {}

  .code {
    .register-code {
      padding-left: 10px;
    }
  }
}
</style>
